<template>
  <!-- 顶部导航 -->
  <TopNavBar :title="_t18('22_zichan')">
    <template #right>
      <!-- ✅ 新增：右上角客服图标 -->
      <img
        src="/static/img/Ki8_df270a6e_5CB.63a2943f.png"
        alt="service"
        class="service-icon"
        @click="$router.push('/service')"
      />
    </template>
  </TopNavBar>

  <div style="height: 20px;"></div>

  <!-- ✅ 下拉刷新包裹整个页面 -->
  <van-pull-refresh v-model:loading="refreshing" @refresh="onRefresh">

    <div>
      <div class="custom-tabs">
        <div
          v-for="(item, index) in tabList"
          :key="index"
          :class="['custom-tab', { active: tabActive === item.name }]"
          @click="() => { tabActive = item.name; clickTab({ name: item.name }) }"
        >
          {{ item.keyStr }}
        </div>
      </div>

      <!-- 平台资产 -->
      <Plat
        v-show="tabActive == 'all'"
        :amountSum="amountSum"
        :assetDetails="assetDetails"
        @handleYanjin="handleYanjin"
        @handleShuaxin="handleShuaxin"
        :showNum="showNum"
        :type="tabActive"
      ></Plat>

      <!-- 理财资产 -->
      <financ
        v-show="tabActive == 'spot'"
        :amountSum="amountSum"
        :assetDetails="assetDetails"
        @handleYanjin="handleYanjin"
        @handleShuaxin="handleShuaxin"
        :showNum="showNum"
        :type="tabActive"
      ></financ>
    </div>
  </van-pull-refresh>
</template>

<script setup>
/* 保持你原来的所有逻辑不变 */
import { _t18 } from '@/utils/public'
import { _add } from '@/utils/decimal'
import Plat from './components/account/platAccount.vue'
import financ from './components/account/financAccount.vue'
import Contarct from './components/account/contarctAccount.vue'
import { priceFormat } from '@/utils/decimal.js'
import { useUserStore } from '@/store/user/index'
import { useMainStore } from '@/store'
import { storeToRefs } from 'pinia'
import { storageDict } from '@/config/dict'
import { showLoadingToast, showToast } from 'vant'
import { getFreezeList } from '@/api/user'
import { onMounted, ref, computed } from 'vue'
import { DIFF_FREEZE_ASSETS } from '@/config/index'
import { useI18n } from 'vue-i18n'
import { useAssetStore } from '@/store/asset.js'


const { t } = useI18n()
const userStore = useUserStore()
const mainStore = useMainStore()
const assetStore = useAssetStore()

const tabList = ref([
  { name: 'all', keyStr: _t18('22_zichanzh') },
  { name: 'spot', keyStr: _t18('22_zichanxh') }
])

const tabActive = ref(tabList.value[0]?.name || '')
const curIndex = ref('0')
const showNum = ref(localStorage.getItem(storageDict.EYES) == 'true' || true)
const freezeList = ref([])
const refreshing = ref(false)

// ✅ 封装一个带超时保护的工具函数
const withTimeout = (promise, timeout = 5000) =>
  Promise.race([
    promise,
    new Promise((_, reject) =>
      setTimeout(() => reject(new Error('timeout')), timeout)
    )
  ])

// ✅ 新版下拉刷新逻辑（防卡死、带超时）
import { nextTick } from 'vue'

const onRefresh = async () => {
  // 防止重复触发
  if (refreshing.value) return
  refreshing.value = true

  // ✅ 模拟加载动画效果（可选）
  setTimeout(() => {
    refreshing.value = false
    location.reload() // ✅ 直接刷新整个页面
  }, 600)
}






const clickTab = (e) => {
  if (curIndex.value != e.name) {
    userStore.getUserInfo()
    curIndex.value = e.name
  }
}

const handleYanjin = () => {
  showNum.value = !showNum.value
  localStorage.setItem(storageDict.EYES, showNum.value)
}

const handleShuaxin = () => {
  showLoadingToast({
    forbidClick: true,
    duration: 0
  })
  userStore.getUserInfo()
  getAccountFreezeList()
}

const getAccountFreezeList = async () => {
  if (DIFF_FREEZE_ASSETS.includes(__config._APP_ENV)) {
    const res = await getFreezeList()
    if (res.code == '200') {
      freezeList.value = res.data
    }
  }
}

const { asset } = storeToRefs(userStore)
const assetDetails = computed(() => {
  let list = []
  asset.value.forEach((item) => {
    if (
      (item.type == 1 && tabActive.value == '平台资产') ||
      (item.type == 2 && tabActive.value == '理财资产') ||
      (item.type == 3 && tabActive.value == '合约资产')
    ) {
      let obj = {}
      obj['keyong'] = priceFormat(item.availableAmount)
      if (DIFF_FREEZE_ASSETS.includes(__config._APP_ENV)) {
        let temp = 0
        if (freezeList.value) {
          freezeList.value.forEach((itm) => {
            if (itm.coin == item.symbol && item.type == 1) temp = itm.price
          })
        }
        obj['zhanyong'] = priceFormat(_add(item.occupiedAmount, temp))
      } else {
        obj['zhanyong'] = priceFormat(item.occupiedAmount)
      }
      obj['zhehe'] = priceFormat(item.exchageAmount)
      if (item.symbol == 'usdt') {
        obj['icon'] = 'usdt'
        obj['loge'] = item.loge
        obj['title'] = 'USDT'
        list.unshift(obj)
      } else {
        obj['loge'] = item.loge
        obj['title'] = item.symbol?.replace('usdt', '').trim().toLocaleUpperCase()
        obj['icon'] = item.symbol?.replace('usdt', '').trim()
        list.push(obj)
      }
    }
  })
  return list
})

const amountSum = computed({
  get() {
    let sum = 0
    const allAssets = userStore.asset || []  // ✅ 确保依赖 userStore.asset 响应式

    if (tabActive.value === 'spot') {
      // 现货资产：type=9
      allAssets.forEach(item => {
        if (item.type === 9) {
          sum += Number(item.exchageAmount || 0)
        }
      })
    } else {
      // 总资产：保留原逻辑
      allAssets.forEach(item => {
        sum += Number(item.exchageAmount || 0)
      })
    }

    assetStore.setAmountSum(sum)
    return priceFormat(sum)
  },
  set(value) {
    assetStore.setAmountSum(value)
  }
})


onMounted(() => {
  getAccountFreezeList()

  // ✅ 每秒更新资产数据
  const timer = setInterval(() => {
    userStore.getUserInfo()
  }, 1000)

  onUnmounted(() => clearInterval(timer))
})
</script>

<style lang="scss" scoped>
.custom-tabs {
  display: flex;
  align-items: center;
  background: #f6f7f8;
  padding: 10px 0 10px 16px; /* ✅ 调小上下间距 */
  margin-top: -6px; /* ✅ 向上移动一点 */
}

.custom-tab {
  padding: 10px 24px;
  border-radius: 24px;
  color: #222;
  font-weight: bold;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s;
  border: none;
  outline: none;
  box-shadow: none;
  user-select: none;
}

.custom-tab.active {
  background: #000;
  color: #fff;
}

/* ✅ 新增客服图标样式 */
.service-icon {
  width: 38px;
  height:38px;
  border-radius: 50%;
  cursor: pointer;
  padding: 3px;
  background: #fff;
  box-shadow: 0 0 4px rgba(0, 0, 0, 0.15);
  transition: transform 0.2s ease;
}
.service-icon:hover {
  transform: scale(1.1);
}

:deep(.van-tabs__wrap) {
  height: 60px;
  border-bottom: 1px solid var(--ex-border-color);
  background: var(--ex-home-list-bgcolor) !important;

  .van-tab__text {
    font-size: 16px;
    font-weight: normal;
  }

  .van-tab--shrink {
    margin-right: 20px;
  }
}

:deep(.van-tabs__nav) {
  background: var(--ex-home-list-bgcolor) !important;
}

:deep(.van-tab) {
  color: var(--ex-home-list-ftcolor) !important;
}

:deep(.van-tab--active) {
  color: var(--ex-home-list-ftcolor3) !important;
}
</style>
